package com.zhu.utils;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.pool.DruidPooledConnection;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.zhu.config.JDBCConfig;
import redis.clients.jedis.Jedis;

import java.lang.reflect.InvocationTargetException;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;

/**
 *查询维表数据进一步封装
 */
public class DIMUtils {


    public static JSONObject getDimInfo(Connection connection,String tableName,String key) throws InvocationTargetException {

        //todo 先查询redis string <tableNAME + id,data>
        Jedis jedis = RedisUtil.getJedis();
        String redisKey = "Flink_GMALL_DIM:" + tableName + ":" +key;
        String dimJsonStringData = jedis.get(redisKey);
        if (dimJsonStringData != null){
            //重置过期时间
            jedis.expire(redisKey,26 * 60 * 60);
            //归还连接
            jedis.close();
            //返回数据
            return JSON.parseObject(dimJsonStringData);
        }

        //todo 如果redis没有 查询Hbase

        //sql
        String sql = "select * from " + JDBCConfig.HBASE_SCHEMA + "." + tableName +" where id = '" + key + "'";
        System.out.println(sql);
        List<JSONObject> queryList = JDBCUtil.queryList(connection, sql, JSONObject.class, false);


        //计算平均查询时间  150-200 ms 主键查询  1s 只处理八九条数据
        /*
        hbase 读取数据

        client 查元数据  zk metastore所在的位置  ,将metastore缓存到本地
        从metastore 表中找到目标表的位置  regionServer
        phoenix 真正速度 8 - 10 ms
        使用 redis  0.5ms  1个并行度 1s处理 1000条数据
         */
        //todo 将查询的数据写入 redis
        JSONObject dimInfo = queryList.get(0);
        jedis.set(redisKey,dimInfo.toJSONString());
        //设置过期时间
        jedis.expire(redisKey, 24 * 60 * 60);
        jedis.close();
        return dimInfo;
    }


    /**
     *  修改数据 旧数据  redis可以删除不存在的数据
     * @param tableName  表名
     * @param key 主键id
     */
    public static void delDimInfo(String tableName,String key){

        //获取连接
        Jedis jedis = RedisUtil.getJedis();
        String redisKey = "Flink_GMALL_DIM:" + tableName + ":" +key;
        jedis.del(redisKey);
        jedis.close();
    }



    /*
    public static void main(String[] args) throws SQLException, InvocationTargetException {
        DruidDataSource dataSource = ZhuDruidDataSourceUtil.createDataSource();
        DruidPooledConnection connection = dataSource.getConnection();

        long start1 = System.currentTimeMillis();
        JSONObject dimInfo = getDimInfo(connection, "DIM_BASE_TRADEMARK", "12");
        long end1 = System.currentTimeMillis();
        JSONObject dimInfo2 = getDimInfo(connection,"DIM_BASE_TRADEMARK","12");
        long end2 = System.currentTimeMillis();
        System.out.println(dimInfo);
        System.out.println(dimInfo2);
        System.out.println(end1-start1);    //优化前 300 ms  优化后 90ms
        System.out.println(end2-start1);
        connection.close();


    }

     */

}
